package com.hmall.web;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.constants.MqConstants;
import com.hmall.service.IItemService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("item")
@Slf4j
public class ItemController {

    @Autowired
    private IItemService itemService;
    @Autowired
    private RabbitTemplate rabbitTemplate;


    @GetMapping("list")
    public PageDTO<Item> itemPage(
            @RequestParam("page") Integer page,
            @RequestParam("size") Integer size,
            @RequestHeader(name = "authorization",required = true) String authorization
            )
    {
        System.out.println("authorization="+authorization);
        log.info("page,size:{},{}", page, size);

        IPage<Item> pages = new Page(page, size);

        itemService.page(pages);

        PageDTO<Item> pageDTO = new PageDTO<>();

        pageDTO.setTotal(pages.getTotal());

        pageDTO.setList(pages.getRecords());
        return pageDTO;
    }


    @GetMapping("{id}")
    public Item getItemId(@PathVariable("id") Long id) {

        log.info("id:{}", id);

        Item item = itemService.getById(id);

        return item;
    }

    @PostMapping
    public void addItem(@RequestBody Item item) {
        log.info("item:{}", item);

        itemService.save(item);
    }

    @PutMapping
    public void updateItem(@RequestBody Item item) {
        log.info("item:{}", item);

        itemService.updateById(item);
    }

    @PutMapping("/status/{id}/{status}")
    public void updateStatus(@PathVariable("id") Long id, @PathVariable("status") Integer status) {

        Item item = new Item();
        item.setId(id);
        item.setStatus(status);

        itemService.updateById(item);

        if (status == 1) {
            rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE, MqConstants.HOTEL_INSERT_KEY, id);
        } else {
            rabbitTemplate.convertAndSend(MqConstants.HOTEL_EXCHANGE, MqConstants.HOTEL_DELETE_KEY, id);
        }


    }

    @DeleteMapping("{id}")
    public void deleteById(@PathVariable("id") Long id) {

        itemService.removeById(id);
    }
}
